<?php
    /*
     * Маппер для блогов, тут вроде ничего необычного нет
     */
class Model_BlogsMapper 
{
    protected $_dbTable;

    public function __construct($dbTable = null){
        if($dbTable === null){
            $this->setDbTable(new Model_DbTable_Blog());
        } else {
           $this->setDbTable($dbTable);
        }
    }
    
    public function setDbTable(Zend_Db_Table_Abstract $dbTable)
    {
        $this->_dbTable = $dbTable;
    }
    
    public function getDbTable()
    {
        return $this->_dbTable;
    }
    
    public function save(Model_Blog $blog)
    {   
        $data = array(
            'id'   => $blog->id,
            'name' => $blog->name
        );
        if($blog->id === null){
            $blogId = $this->_dbTable->insert($data);
            $blog->id = $blogId;
        } else {
            $this->_dbTable->update($data, array('id = ?' => (integer) $blog->id));
        }
        return $blog;
    }
    
    public function delete(Model_Blog $blog){
        if($blog->id){
            $this->_dbTable->delete(array('id = ?' => (integer) $blog->id));
        }
    }
    
    public function find($id)
    {
        $row = $this->_dbTable->find($id)->current();
        if($row){
            return new Model_Blog(
                array(
                    'id'  => $row->id, 
                    'name'=> $row->name
                )
            );
        } else {
            return null;
        }
    }
    
    public function getAll()
    {
        $blogs = array();
        foreach($this->_dbTable->fetchAll() as $blogRow){
            $blogs[] = new Model_Blog($blogRow->toArray());
        } 
        return $blogs;
    }
    
    public function  findBlogByPost($post)
    {
        return $this->find($post->blog_id);
    }
}